import { useRequest } from 'ahooks';
import { AutoComplete, Spin } from 'antd';
import React, { forwardRef, useState } from 'react';
import { HTTP_CALL_REQUEST_URL_SCENE } from '@/pages/ServerEndpointManager';
import request from '@/utils/request';

const { Option } = AutoComplete;

function FakeLoading() {
  return (
    <Spin spinning>
      <AutoComplete placeholder="接口地址" />
    </Spin>
  );
}

const prefix = 'refs/endpoints/';

function getInputValue(value, endpoints) {
  if (!value) {
    return value;
  }
  if (value.startsWith(prefix)) {
    const parts = value.split('/');
    const endpointCode = parts[parts.length - 1];
    const ep = endpoints.find(ep => ep.endpointCode === endpointCode);
    return ep ? ep.endpointUrl : value;
  }
  return value;
}

function HttpCallUrlInput({ value, onChange }, ref) {
  const { data = [], loading } = useRequest(() =>
    request.get(`/serverEndpoint/listByScene?scene=${HTTP_CALL_REQUEST_URL_SCENE}`)
  );

  if (loading) {
    return <FakeLoading />;
  }

  const inputValue = getInputValue(value, data);

  const autoCompleteOptions = data.map(ep => (
    <Option key={ep.endpointId} value={`refs/endpoints/${ep.endpointCode}`}>
      {`${ep.endpointName}(${ep.endpointUrl})`}
    </Option>
  ));

  return (
    <AutoComplete
      value={inputValue}
      onChange={v => {
        if (!v) {
          onChange(v);
        } else if (!v.startsWith(prefix)) {
          onChange(v);
        }
      }}
      onSelect={onChange}
      placeholder="接口地址"
      allowClear
      optionLabelProp="value"
      filterOption={(inputValue, option) =>
        option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
      }
    >
      {autoCompleteOptions}
    </AutoComplete>
  );
}

export default forwardRef(HttpCallUrlInput);
